import modelExtend from 'dva-model-extend'
import { pathMatchRegexp } from 'utils'
import api from 'api'
import { pageModel } from 'utils/model'
import { message } from 'antd'

const { <#list forms as form><#if (form.type=='Select')>get${form.name?cap_first}Tree,</#if></#list>query${api?cap_first},create${api?cap_first},update${api?cap_first},remove${api?cap_first} }=api

export default modelExtend(pageModel, {
	namespace: '${namespace}',

	state: {
		editingKey:'',
    	editType:'',
    	filterItem:{},<#list forms as form><#if (form.type=='Select')>
		${form.name}Tree:[],</#if></#list>
	},

	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(location => {
				const {pathname, query}=location
				if (pathMatchRegexp('${url}', pathname)) {
					const payload = {...query, page: 1, pageSize: 10 }
					dispatch({
						type: 'query',
						payload,
					})
					<#list forms as form><#if (form.type=='Select')>
					dispatch({type: 'get${form.name?cap_first}Tree'})
					</#if></#list>
				}
			})
		},
	},

	effects: {
		*query({ payload = {} }, { call, put }) {
			const data = yield call(query${api?cap_first}, payload)
			const {error,result}=data
			if (!error) {
				yield put({
					type: 'querySuccess',
					payload: {
						list: result.rows,
						pagination: {
							current: Number(payload.page) || 1,
							pageSize: Number(payload.pageSize) || 10,
							total: result.total,
						},
					},
				})
			}
		},
		<#list forms as form><#if (form.type=='Select')>
		*get${form.name?cap_first}Tree({ payload = {} }, { call, put }) {
			const {error,result} = yield call(get${form.name?cap_first}Tree, payload)
			if (!error) {
				yield put({
					type: 'updateState',
					payload: {
						${form.name}Tree:result
					},
				})
			}
		},</#if></#list>
		
		*remove({ payload }, { call, put, select }) {
			const {error} = yield call(remove${api?cap_first}, payload)
			if (!error) {
				message.success('操作成功')
			} else {
				message.error('操作失败')
			}
			return error
		},

		*create({ payload }, { call, put }) {
			const {error} = yield call(create${api?cap_first}, payload)
			if (!error) {
				message.success('操作成功')
				yield put({ type: 'hideModal' })
			} else {
				message.error('操作失败')
			}
			return error
		},

		*update({ payload }, { select, call, put }) {
			const {error} = yield call(update${api?cap_first}, payload)
			if (!error) {
				message.success('操作成功')
				yield put({ type: 'hideModal' })
			} else {
				message.error('操作失败')
			}
			return error
		},
	},

	reducers: {
		showModal(state, { payload }) {
			return { ...state, ...payload, modalVisible: true }
		},

		hideModal(state) {
			return { ...state, modalVisible: false }
		},
	},

})
